<template>
  <div class="chat-box">
    <!-- 顶部 -->
    <div class="chatbox-top">
      <div class="chatbox-top-left">{{ name }}</div>
      <div class="chatbox-top-right">
        <el-button class="esc-button" @click="esc">返回</el-button>
      </div>
    </div>
    <!-- 聊天内容 -->
    <div class="chatbox-middle">
      <div v-for="(item, index) in messageList" :key="index" class="message-item"
        :class="{ 'flex-right': item.sendUserId === userInfo.userId, 'flex-left': item.sendUserId !== userInfo.userId }">
        <!-- 左：接收者消息 -->
        <div v-if="item.sendUserId !== userInfo.userId" class="flex-left">
          <div class="avatar">
            <img src="../assets/fasongzhe.jpg" alt="avatar">
          </div>
          <div class="message-content">
            {{ item.message }}
          </div>
        </div>
        <!-- 右：发送者消息 -->
        <div v-else class="flex-right">
          <div class="message-content">
            {{ item.message }}
          </div>
          <div class="avatar">
            <img src="../assets/jieshouzhe.jpg" alt="avatar">
          </div>
        </div>
      </div>
    </div>
    <!-- 聊天框 -->
    <div class="chatbox-bottom">
      <div>
        <el-input v-model="inputMessage" placeholder="请输入内容" @keyup.enter="sendMessage"></el-input>
      </div>
      <div class="button">
        <el-button @click="sendMessage">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  computed: {
    ...mapGetters('chat', [
      'getMessages',
      'getWebSocket',
      'getSelectedUser',
    ]),
    messageList() {
      return this.getMessages;
    },
    ws() {
      return this.getWebSocket;
    },
  },
  methods: {
    ...mapActions('chat', [
      'connectWebSocket',
      'sendMessageToServer',
    ]),
    sendMessage() {
      if (this.inputMessage.trim() === "") {
        this.$message.warning("消息不能为空");
        return;
      }

      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        const message = {
          type: "message",
          sendUserId: this.userInfo.userId,
          receivUserId: this.getSelectedUser?.id,
          message: this.inputMessage,
        };
        this.sendMessageToServer(message);
        this.inputMessage = ""; // 清空输入框
      } else {
        this.$message.error("WebSocket 连接未建立");
      }
    },
    esc() {
      this.$router.push('/');
    },
  },
  data() {
    return {
      name: "聊天室",
      userInfo: {
        userId: "",
      },
      inputMessage: "",
    };
  },
  mounted() {
    const username = localStorage.getItem("username");
    const userId = localStorage.getItem("userId");

    if (!username || !userId) {
      this.$router.push("/login");
      return;
    }

    this.userInfo.userId = userId;
    this.name = username;

    this.connectWebSocket();

    this.$bus.$on('appear', (name) => {
      this.name = name;
    });
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
    this.$bus.$off('appear');
  },
};
</script>

<style lang="scss" scoped>
.chat-box {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;

  .chatbox-top {
    height: 60px;
    padding: 15px;
    border-bottom: 1px solid #e0e0e0;
    font-size: 18px;
    font-weight: bold;
    color: #333333;
    background-color: #f9f9f9;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .chatbox-top-left {
      flex: 1;
    }

    .chatbox-top-right {
      .esc-button {
        background-color: #f56c6c;
        border-color: #f56c6c;
        color: #ffffff;
        font-weight: bold;
        padding: 8px 16px;
        border-radius: 4px;

        &:hover {
          background-color: #e65a5a;
          border-color: #e65a5a;
        }

        &:active {
          background-color: #d44a4a;
          border-color: #d44a4a;
        }
      }
    }
  }

  .chatbox-middle {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
    background-color: #f5f5f5;


    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #c1c1c1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f1f1f1;
    }

    .message-item {
      margin-bottom: 15px;
      display: flex;

      &.flex-left {
        flex-direction: row;

        .message-content {
          background-color: #e3f2fd; // 浅蓝色
          color: #333333;
          border-radius: 10px 10px 10px 0;
        }
      }

      &.flex-right {
        justify-content: flex-end;

        .message-content {
          background-color: #dcedc8;
          color: #333333;
          border-radius: 10px 10px 0 10px;
        }
      }

      .message-content {
        max-width: 70%;
        padding: 10px 15px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        word-break: break-word;
      }

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }

  .chatbox-bottom {
    height: 120px;
    padding: 15px;
    border-top: 1px solid #e0e0e0;
    background-color: #ffffff;

    .button {
      ::v-deep .el-button {
        background-color: #67c23a;
        border-color: #67c23a;
        color: #ffffff;
        margin-left: 10px;

        &:hover {
          background-color: #5daf36;
          border-color: #5daf36;
        }

        &:active {
          background-color: #529b2f;
          border-color: #529b2f;
        }
      }
    }

    ::v-deep .el-input__inner {
      border: none;
      box-shadow: none;
      outline: none;
    }
  }
}
</style>